import { defineStore } from 'pinia';
import axios from 'axios';

export const useTaskStore = defineStore('task', {
    state: () => ({
        tasks: [],
        newTask: { title: '', description: '' },
    }),
    actions: {
        async fetchTasks() {
            const response = await axios.get(`${import.meta.env.VITE_API_URL}/tasks`);
            this.tasks = response.data;
        },
        async addTask() {
            const response = await axios.post(`${import.meta.env.VITE_API_URL}/tasks`, this.newTask);
            this.tasks.push(response.data);
            this.newTask = { title: '', description: '' };
        },
        async updateTask(task) {
            await axios.put(`${import.meta.env.VITE_API_URL}/tasks/${task.id}`, task);
            await this.fetchTasks();
        },
        async deleteTask(id) {
            await axios.delete(`${import.meta.env.VITE_API_URL}/tasks/${id}`);
            this.tasks = this.tasks.filter(task => task.id !== id);
        },
    }
});